/*
 * *****************************************************************************
 *  Copyright ( c ) 2019 huibur Inc. All Rights Reserved.
 *
 *  This software is the confidential and proprietary information of Huibur Inc
 *  (*Confidential Information*). You shall not disclose such Confidential Information
 *  and shall use it only in accordance with the terms of the license agreement
 *  you entered into with Huibur or a Huibur authorized
 *  reseller (the "License Agreement*).
 *  ******************************************************************************
 */

package com.huibur.devicecheck.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.huibur.devicecheck.config.SaticScheduleTask;
import com.huibur.devicecheck.enums.DeviceEnums;
import com.huibur.devicecheck.enums.TaskRecordEnums;
import com.huibur.devicecheck.exception.TaskRecordAlreadyExistException;
import com.huibur.devicecheck.mapper.DeviceMapper;
import com.huibur.devicecheck.mapper.TaskRecordDataMapper;
import com.huibur.devicecheck.mapper.TaskRecordMapper;
import com.huibur.devicecheck.model.param.TaskRecordParam;
import com.huibur.devicecheck.model.po.DevicePO;
import com.huibur.devicecheck.model.po.TaskRecordDataPO;
import com.huibur.devicecheck.model.po.TaskRecordPO;
import com.huibur.devicecheck.model.query.TaskRecordQuery;
import com.huibur.devicecheck.model.vo.RecordStatusVO;
import com.huibur.devicecheck.model.vo.StatisticVO;
import com.huibur.devicecheck.model.vo.TaskRecordVO;
import com.huibur.devicecheck.request.ObjRes;
import com.huibur.devicecheck.request.PageRes;
import com.huibur.devicecheck.request.SessionContext;
import com.huibur.devicecheck.service.ITaskRecordService;
import com.huibur.devicecheck.utils.ConvertPageUtil;
import com.huibur.devicecheck.utils.DateUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import java.sql.Timestamp;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
import java.util.stream.Collectors;

/*******************************************************
* Title: TaskRecordServiceImpl.java
* Description:
* @author baiqingshuo
* @date 2021/9/24
* @version 1.0
*******************************************************/
@Service
public class TaskRecordServiceImpl extends ServiceImpl<TaskRecordMapper, TaskRecordPO> implements ITaskRecordService {

    @Autowired
    TaskRecordMapper taskRecordMapper;
    @Autowired
    TaskRecordDataMapper taskRecordDataMapper;
    @Autowired
    DeviceMapper deviceMapper;

    /**
     * 新增检修记录
     *
     * @param taskRecordParam
     * @return
     */
    @Override
    public ObjRes<Void> insert(TaskRecordParam taskRecordParam) {
        TaskRecordPO taskRecordPO = taskRecordMapper.selectOne(new LambdaQueryWrapper<TaskRecordPO>()
                .eq(TaskRecordPO::getRecord, taskRecordParam.getRecord())
                .ne(TaskRecordPO::getIsDeleted, TaskRecordEnums.DELETE.getCode()));
        if (null != taskRecordPO) {
            throw new TaskRecordAlreadyExistException();
        }

        TaskRecordPO taskRecord = new TaskRecordPO();
        taskRecord.setTaskId(taskRecordParam.getTaskId());
        taskRecord.setDeviceLabel(taskRecordParam.getDeviceLabel());
        taskRecord.setUserId(taskRecordParam.getUserId());
        taskRecord.setRecord(taskRecordParam.getRecord());
        taskRecord.setImage(taskRecordParam.getImage());
        taskRecord.setIsDeleted(TaskRecordEnums.NORMAL.getCode());
        taskRecord.setCreateAt(DateUtils.getCurrentTimestamp());
        taskRecord.setCreateBy(SessionContext.getCurrentUserSubject().getUserId());
        taskRecordMapper.insert(taskRecord);
        return new ObjRes<Void>().success("创建成功");
    }

    /**
     * 删除检修记录
     *
     * @param id
     * @return
     */
    @Override
    public Boolean deleteById(Long id) {
        TaskRecordPO taskRecordPO = new TaskRecordPO();
        taskRecordPO.setId(id);
        taskRecordPO.setIsDeleted(TaskRecordEnums.DELETE.getCode());
        taskRecordMapper.updateById(taskRecordPO);
        return true;
    }

    /**
     * 编辑检修记录
     *
     * @param id
     * @param taskRecordParam
     * @return
     */
    @Override
    public ObjRes<Void> updateTaskRecord(Long id, TaskRecordParam taskRecordParam) {
        TaskRecordPO taskRecord = taskRecordMapper.selectOne(new LambdaQueryWrapper<TaskRecordPO>()
                .ne(TaskRecordPO::getId, id)
                .eq(TaskRecordPO::getRecord, taskRecordParam.getRecord())
                .ne(TaskRecordPO::getIsDeleted, TaskRecordEnums.DELETE.getCode()));
        if (null != taskRecord) {
            throw new TaskRecordAlreadyExistException();
        }
        TaskRecordPO taskRecordPO = new TaskRecordPO();
        taskRecordPO.setTaskId(taskRecordParam.getTaskId());
        taskRecordPO.setDeviceLabel(taskRecordParam.getDeviceLabel());
        taskRecordPO.setUserId(taskRecordParam.getUserId());
        taskRecordPO.setRecord(taskRecordParam.getRecord());
        taskRecordPO.setImage(taskRecordParam.getImage());
        taskRecordPO.setIsDeleted(TaskRecordEnums.NORMAL.getCode());
        taskRecordPO.setUpdateAt(DateUtils.getCurrentTimestamp());
        taskRecordPO.setUpdateBy(SessionContext.getCurrentUserSubject().getUserId());
        taskRecordMapper.update(taskRecordPO, new LambdaQueryWrapper<TaskRecordPO>()
                .eq(TaskRecordPO::getId, id));
        return new ObjRes<Void>().success("修改成功");
    }

    /**
     * 检修记录列表(查询并分页)
     *
     * @param taskRecordQuery
     * @return
     */
    @Override
    public PageRes<TaskRecordVO> selectListTaskRecord(TaskRecordQuery taskRecordQuery) {
        Page<TaskRecordPO> page = new Page<>(taskRecordQuery.getCurrent(), taskRecordQuery.getPageSize());
        IPage<TaskRecordVO> pages = taskRecordMapper.selectListTaskRecord(page, taskRecordQuery);
        return ConvertPageUtil.convertPage(taskRecordQuery.getCurrent(), page.getTotal(), pages.getRecords());
    }
    /**
     * 获取检修记录详情
     *
     * @param id
     * @return
     */
    @Override
    public TaskRecordVO selectByListTaskRecord(Long id) {
        return taskRecordMapper.selectByListTaskRecord(id);
//        TaskRecordPO taskRecordPO = taskRecordMapper.selectOne(new LambdaQueryWrapper<TaskRecordPO>()
//                .eq(TaskRecordPO::getId, id));
//        TaskRecordVO taskRecordVO = new TaskRecordVO();
//        taskRecordVO.setTaskId(taskRecordPO.getTaskId());
//        taskRecordVO.setDeviceLabel(taskRecordPO.getDeviceLabel());
//        taskRecordVO.setUserId(taskRecordPO.getUserId());
//        taskRecordVO.setRecord(taskRecordPO.getRecord());
//        taskRecordVO.setImage(taskRecordPO.getImage());
//        taskRecordVO.setIsDeleted(taskRecordPO.getIsDeleted());
//        taskRecordVO.setCreateAt(taskRecordPO.getCreateAt());
//
//        List<TaskRecordDataPO> taskRecordDataList = taskRecordDataMapper.selectList(new LambdaQueryWrapper<TaskRecordDataPO>()
//                .eq(TaskRecordDataPO::getTaskRecordId, id));
//        taskRecordVO.setTaskRecordDataPOList(taskRecordDataList);

    }

    /**
     * 根据用户id获取检修记录
     *
     * @param id
     * @return
     */
    @Override
    public List<TaskRecordVO> findTaskRecordByUserId(Long id) {
        return  taskRecordMapper.findTaskRecordByUserId(id);
    }

    /**
     * 根据设备唯一标识获取检修记录
     *
     * @param deviceLabel
     * @return
     */
    @Override
    public List<TaskRecordVO> findTaskRecordByDeviceLabel(String deviceLabel) {
        return taskRecordMapper.findTaskRecordByDeviceLabel(deviceLabel);
    }

    /**
     * 根据任务id获取检修记录
     *
     * @param id
     * @return
     */
    @Override
    public List<TaskRecordVO> findTaskRecordByTaskId(Long id) {
        return taskRecordMapper.findTaskRecordByTaskId(id);

    }

    /**
     * 移动端检修记录列表(查询并分页)
     * @param taskRecordQuery
     * @return
     */
    @Override
    public PageRes<TaskRecordVO> selectTaskRecordList(TaskRecordQuery taskRecordQuery) {
        Page<TaskRecordPO> page = new Page<>(taskRecordQuery.getCurrent(), taskRecordQuery.getPageSize());
        IPage<TaskRecordVO> pages = taskRecordMapper.selectTaskRecordList(page, taskRecordQuery);
        return ConvertPageUtil.convertPage(taskRecordQuery.getCurrent(), page.getTotal(), pages.getRecords());
    }

    /**
     * 后台管理端首页统计图（状态统计）
     * @return
     */
    @Override
    public RecordStatusVO statistics() throws ParseException {
        Calendar cal = Calendar.getInstance();
        //获取年份
        int year = cal.get(Calendar.YEAR);
        //获取月份
        int month = cal.get(Calendar.MONTH) + 1;
        //获取当前月最第一天
        String firstDayOfMonth = TaskRecordServiceImpl.getFirstDayOfMonth(month);
        //获取当前月最后一天
        String lastDayOfMonth = TaskRecordServiceImpl.getLastDayOfMonth(month);

        String format = "yyyy-MM-dd HH:mm:ss";
        SimpleDateFormat sdf = new SimpleDateFormat(format);
        Timestamp firstTimestamp = new Timestamp(sdf.parse(firstDayOfMonth).getTime());
        Timestamp lastTimestamp = new Timestamp(sdf.parse(lastDayOfMonth).getTime());

//        List<String> normalList = taskRecordMapper.selectMonthNormalList(firstTimestamp, lastTimestamp);
//        List<String> abnormalList = taskRecordMapper.selectMonthAbnormalList(firstTimestamp,lastTimestamp);

        RecordStatusVO recordStatusVO = new RecordStatusVO();
        //统计图中直接将两组数据查出来
        List<StatisticVO> statisticVOList = taskRecordMapper.selectStatusNum(firstTimestamp, lastTimestamp);
        for (StatisticVO statisticVO : statisticVOList) {
            //状态为0 则为  正常状态的个数
            if (statisticVO.getStatus().equals(0)) {
                recordStatusVO.setNormalCount(statisticVO.getNum());
            }
            //状态为1 则为  异常状态的个数
            if (statisticVO.getStatus().equals(1)) {
                recordStatusVO.setAbnormalCount(statisticVO.getNum());
            }
        }
        recordStatusVO.setNormalCount(recordStatusVO.getNormalCount() == null ? 0 : recordStatusVO.getNormalCount());
        recordStatusVO.setAbnormalCount(recordStatusVO.getAbnormalCount() == null ? 0 : recordStatusVO.getAbnormalCount());

        //查询当月的所有记录
        List<TaskRecordVO> taskRecordVOList = taskRecordMapper.selectMonthList(firstTimestamp,lastTimestamp);
        //设备唯一标识抽成一个list
        List<String> collect = taskRecordVOList.stream().map(item -> item.getDeviceLabel()).collect(Collectors.toList());

        //查询出设备表中所有的设备的唯一标识
        List<DevicePO> devicePOList = deviceMapper.selectList(new LambdaQueryWrapper<DevicePO>()
                .eq(DevicePO::getIsDeleted, DeviceEnums.NORMAL));
        List<String> collect1 = devicePOList.stream().map(item -> item.getLabel()).collect(Collectors.toList());
        //移除掉相同的设备唯一标识
        collect1.removeAll(collect);
        //获取到没检查的设备个数
        recordStatusVO.setNotCheckCount(collect1.size());
        return recordStatusVO;
    }

    /**
     * 获取当前月第一天
     * @param month
     * @return
     */
    public static String getFirstDayOfMonth(int month) {
        Calendar calendar = Calendar.getInstance();
        // 设置月份
        calendar.set(Calendar.MONTH, month - 1);
        // 获取某月最小天数
        int firstDay = calendar.getActualMinimum(Calendar.DAY_OF_MONTH);
        // 设置日历中月份的最小天数
        calendar.set(Calendar.DAY_OF_MONTH, firstDay);
        // 格式化日期
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        String firstDay1 = sdf.format(calendar.getTime())+" 00:00:00";
        return firstDay1;
    }

    //获取当前月最后一天：
    public static String getLastDayOfMonth(int month) {
        Calendar calendar = Calendar.getInstance();
        // 设置月份
        calendar.set(Calendar.MONTH, month - 1);
        // 获取某月最大天数
        int maxDay = 0;
        //2月的平年瑞年天数
        if(month==2) {
            maxDay = calendar.getLeastMaximum(Calendar.DAY_OF_MONTH);
        }else {
            maxDay = calendar.getActualMaximum(Calendar.DAY_OF_MONTH);
        }
        // 设置日历中月份的最大天数
        calendar.set(Calendar.DAY_OF_MONTH, maxDay);
        // 格式化日期
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        String lastDay = sdf.format(calendar.getTime())+" 23:59:59";

        return lastDay;
    }
}